<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;

class Category extends Common
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        $cate = get_cates('category', 0);
        $this->assign('cate', $cate);
        return view();
    }

    // 添加/编辑客服
    public function save_category() {
        $id = input('param.id', 0);
        // 获取分类树
        $ztree = Ztree($id);
        $this->assign('ztree', $ztree);
        if (Request::instance()->isPost()) {
            // 提交数据
            $data = [
                'pid' => input('param.pid'),
                'name' => input('param.name'),
                'level' => 1
            ];
            if (input('param.pid') > 0) {
                $cate = db('category')->where('id', input('param.pid'))->find();
                if ($cate['level'] >= 2) {
                    return json(['code' => 0, 'msg' => '分类最多二级，请确认！']);
                } else{
                    $data['level'] = $cate['level'] + 1;
                }
            }

            if ($id > 0)  {
                $text = '编辑';
                $rs = db('category')->where('id', $id)->update($data);
            } else {
                $text = '添加';
                $rs = db('category')->insert($data);
            }
            if ($rs !== false)
                return json(['code' => 200, 'msg' => $text . '分类成功！', 'url' => url('index')]);
            else
                return json(['code' => 0, 'msg' => $text . '分类失败！']);
        } else {
            $text = $id > 0 ? '编辑' : '添加';
            $cate = [];
            if ($id > 0) {
                $cate = db('category')->where('id', $id)->find();
            }
            $this->assign('cate', $cate);
            $this->assign('text', $text);
            return view();
        }
    }

    // 删除分类
    public function del_cate() {
        $id = input('param.id', 0);
        $products = db('product')->where('cate_id', $id)->count();
        if ($products > 0) {
            return json(['code' => 0, 'msg' => '分类下面有产品，不能删除！']);
        }

        $category = db('category')->where('pid', $id)->count();
        if ($category > 0) {
            return json(['code' => 0, 'msg' => '分类下面有子类，不能删除！']);
        }
        $rs = db('category')->where('id', $id)->delete();
        if ($rs !== false) {
            return json(['code' => 200, 'msg' => '删除成功！']);
        } else {
            return json(['code' => 0, 'msg' => '删除失败！']);
        }
    }
}
